package com.peng.mybatis.session.defaults;

import com.peng.mybatis.executor.Executor;
import com.peng.mybatis.mapping.MappedStatement;
import com.peng.mybatis.session.Configuration;
import com.peng.mybatis.session.SqlSession;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
@Getter
@SuppressWarnings("all")
public class DefaultSqlSession implements SqlSession {

    private final Configuration configuration;

    private final Executor executor;

    public DefaultSqlSession(Configuration configuration, Executor executor) {
        this.configuration = configuration;
        this.executor = executor;
    }

    @Override
    public <T> T selectOne(String statement) {
        return selectOne(statement, null);
    }

    @Override
    public <T> T selectOne(String statementName, Object parameter) {
        try {
            MappedStatement ms = configuration.getMappedStatement(statementName);
            List<T> res = executor.query(ms, parameter, Executor.NO_RESULT_HANDLER, ms.getBoundSql());
            return res.get(0);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public <T> T getMapper(Class<T> type) {
        return configuration.getMapper(type, this);
    }

}
